
package pl.genapp.stocksense.libraries;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class TwitterHelper {
	
	public static final String SHARED_PREFERENCE_TWITTER = "twitter";
	public static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	public static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	public static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
	
	private static String TWITTER_CONSUMER_KEY = "OMlkXbG9UpfOhLOw473lFg";
	private static String TWITTER_CONSUMER_SECRET = "FB6lfRgtPZ0qov5eqRljNGiIHtyxTLCmE8KzetSHQ";
	
	private static final String TWITTER_CALLBACK_URL = "oauth://twitterCallback";
	
	private static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	
	private SharedPreferences preferences;
	private Context context;
	private static RequestToken requestToken;
	private static Twitter twitter = getTwitterInstance();
	
	public TwitterHelper(Context context) {
		this.context = context;
		preferences = context.getSharedPreferences(SHARED_PREFERENCE_TWITTER, 0);
	}
	
	public boolean isLoggedToTwitter() {
		
		if (preferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false))
			return true;
		else
			return false;
		
	}
	
	static Twitter getTwitterInstance() {
		
		ConfigurationBuilder builder = new ConfigurationBuilder();
		builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
		builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
		Configuration configuration = builder.build();
		
		TwitterFactory factory = new TwitterFactory(configuration);
		return factory.getInstance();
		
	}
	
	public void loginToTwitter() {
		
		new AsyncTask<Void, Void, Void>() {
			
			protected Void doInBackground(Void... params) {
				
				try {
					requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
					context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
				} catch (TwitterException e) {
					e.printStackTrace();
				}
				
				return null;
			}
			
		}.execute();
		
	}
	
	public void twitterReceiveLoginData(Intent intent) {
		
		Log.d("stocksense", "twitterReceiveLoginData");
		
		Uri uri = intent.getData();
		
		if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
			
			final String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
			
			new AsyncTask<Void, Void, AccessToken>() {
				
				protected AccessToken doInBackground(Void... params) {
					
					AccessToken accessToken = null;
					
					try {
						
						accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
						Log.d("stocksense", "after access token");
					} catch (TwitterException e) {
						e.printStackTrace();
					}
					
					return accessToken;
				}
				
				protected void onPostExecute(AccessToken accessToken) {
					super.onPostExecute(accessToken);
					
					Editor editor = preferences.edit();
					
					editor.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					editor.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
					
					editor.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
					editor.commit();
					
					Toast.makeText(context, "Twitter connect - success!", Toast.LENGTH_SHORT).show();
					Log.d("stocksense", "save to prefs");
					
					/**
					 * Any pending actions?
					 */
					/*
					 * StockSenseState state =
					 * (StockSenseState)context.getApplicationContext();
					 * PendingShare pendingShare = state.getPendingShare();
					 * 
					 * if(pendingShare != null && pendingShare.getRequestType()
					 * == PendingShare.SiteType.TWITTER) {
					 * 
					 * postStatusWithImage(pendingShare.getImage(),
					 * pendingShare.getText()); state.setPendingShare(null); }
					 */
				}
			}.execute();
			
		}
		
	}
	
	public void postStatusWithImage(byte[] data, String text) {
		
		Log.d("stocksense", "postStatusWithImage");
		
		InputStream is = new ByteArrayInputStream(data);
		
		final StatusUpdate statusUpdate = new StatusUpdate(text);
		statusUpdate.setMedia("image name", is);
		
		ConfigurationBuilder builder = new ConfigurationBuilder();
		builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
		builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
		
		// Access Token
		preferences = context.getSharedPreferences(SHARED_PREFERENCE_TWITTER, 0);
		String access_token = preferences.getString(PREF_KEY_OAUTH_TOKEN, "");
		// Access Token Secret
		String access_token_secret = preferences.getString(PREF_KEY_OAUTH_SECRET, "");
		
		Log.d("stocksense", access_token + "--!--" + access_token_secret);
		
		AccessToken accessToken = new AccessToken(access_token, access_token_secret);
		final Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
		
		new AsyncTask<Void, Void, twitter4j.Status>() {
			
			protected twitter4j.Status doInBackground(Void... params) {
				
				try {
					return twitter.updateStatus(statusUpdate);
				} catch (TwitterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
			
			protected void onPostExecute(twitter4j.Status result) {
				super.onPostExecute(result);
				
				Toast.makeText(context, "Your Tweet Has Been Posted", Toast.LENGTH_SHORT).show();
				
			}
		}.execute();
		
	}
}
